
#!/usr/bin/python3

import aliLink,mqttd,rpi
import time,json
import Adafruit_DHT
import time
import LCD1602
import flame_sensor
import buzzer_1
import rain_detector
import gas_sensor
import relay
from threading import Thread

pin = 19  # DHT11 温湿度传感器管脚定义
Buzzer = 20    # 有源蜂鸣器管脚定义

# GPIO口定义
sensor = Adafruit_DHT.DHT11




# 三元素（iot后台获取）
ProductKey = 'a11lzCDSgZP'
DeviceName = 'IU6aSETyiImFPSkpcywm'
DeviceSecret = "2551eb5f630c372743c538e9b87bfe6d"
# topic (iot后台获取)
POST = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/event/property/post'  # 上报消息到云
POST_REPLY = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/event/property/post_reply'
SET = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/service/property/set'  # 订阅云端指令


#窗户开关
window = 0
window_status = 0
Thread(target=relay.close).start()

# 消息回调（云端下发消息的回调函数）
def on_message(client, userdata, msg):
    #print(msg.payload)
    Msg = json.loads(msg.payload)

    global window,window_status
    window = Msg['params']['window']
    print(msg.payload)  # 开关值
    if window_status != window:
        window_status = window
        if window == 1:
            Thread(target=relay.open).start()
        else:
            Thread(target=relay.close).start()



#连接回调（与阿里云建立链接后的回调函数）
def on_connect(client, userdata, flags, rc):
    pass



# 链接信息
Server,ClientId,userNmae,Password = aliLink.linkiot(DeviceName,ProductKey,DeviceSecret)

# mqtt链接
mqtt = mqttd.MQTT(Server,ClientId,userNmae,Password)
mqtt.subscribe(SET) # 订阅服务器下发消息topic
mqtt.begin(on_message,on_connect)




# 信息获取上报，每2秒钟上报一次系统参数
while True:
    #获取指示灯状态
    power_stats=int(rpi.getLed())
    if(power_stats == 0):
        power_LED = 0
    else:
        power_LED = 1

    # CPU 信息
    CPU_temp = float(rpi.getCPUtemperature())  # 温度   ℃
    CPU_usage = float(rpi.getCPUuse())         # 占用率 %

    # RAM 信息
    RAM_stats =rpi.getRAMinfo()
    RAM_total =round(int(RAM_stats[0]) /1000,1)    #
    RAM_used =round(int(RAM_stats[1]) /1000,1)
    RAM_free =round(int(RAM_stats[2]) /1000,1)

    # Disk 信息
    DISK_stats =rpi.getDiskSpace()
    DISK_total = float(DISK_stats[0][:-1])
    DISK_used = float(DISK_stats[1][:-1])
    DISK_perc = float(DISK_stats[3][:-1])

    #温度，湿度
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    # LCD显示
    LCD = 0
    try:
        LCD1602.init(0x27, 1)          # 初始化显示屏
        LCD1602.write(0, 0, 'humidity:    ' + str(int(humidity)) + '%')
        LCD1602.write(0, 1, 'temperature: ' + str(int(temperature)) + '\'')  # 在第二行显示world!
        LCD = 1
    except:
        print("显示屏连接不稳定，请检查")
        LCD = 0

    # 蜂鸣器
    buzzer = 0

    # 火焰传感器
    flame_sensor.setup()
    if flame_sensor.fire() == 0:
        flame = 1
        buzzer_1.buzzer_on() #让铃声叫
        buzzer = 1
    else:
        flame = 0
        buzzer_1.buzzer_off() #铃声不叫
        buzzer = 0

    # 烟雾传感器
    gas = gas_sensor.gas()

    # 雨滴传感器
    rain_detector.setup()
    if rain_detector.rain() == 0:
        rain = 1
    else:
        rain = 0

    # 构建与云端模型一致的消息结构
    updateMsn = {
        'cpu_temperature':CPU_temp,
        'cpu_usage':CPU_usage,
        'RAM_total':RAM_total,
        'RAM_used':RAM_used,
        'RAM_free':RAM_free,
        'DISK_total':DISK_total,
        'DISK_used_space':DISK_used,
        'DISK_used_percentage':DISK_perc,
        'PowerLed':power_LED,
        'temperature':temperature,
        'humidity':humidity,
        'window':window,
        'LCD':LCD,
        'buzzer':buzzer,
        'flame':flame,
        'rain':rain,
        'gas':gas
    }
    JsonUpdataMsn = aliLink.Alink(updateMsn)
    print(JsonUpdataMsn)

    mqtt.push(POST,JsonUpdataMsn) # 定时向阿里云IOT推送我们构建好的Alink协议数据

    time.sleep(3)